require("./common/global");
require("./common/newUserSubration");
require("./common/subration");
require("./middlewares/catchError");
const express = require("express");
const http = require("http");
const cookieParser = require("cookie-parser");
const bodyParser = require("body-parser");
const xmlparser = require("express-xml-bodyparser");
const app = express();
const routers = require("./router/index");
app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    res.set("Access-Control-Allow-Credentials", true);
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "content-type");
    //跨域允许的请求方式 
    res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    if (req.method.toLowerCase() == 'options')
        res.send(200); //让options尝试请求快速结束
    else
        next();
});
app.use(express.json()).use(
    express.urlencoded({
        extended: false,
    })
);
app.use(cookieParser());
app
    .use(
        bodyParser.urlencoded({
            limit: "100mb",
            extended: false,
        })
    )
    .use(
        bodyParser.raw({
            limit: "100mb",
        })
    )
    .use(
        bodyParser.text({
            limit: "100mb",
        })
    )
    .use(xmlparser());

/**
 * 将参数接收方式统一改为req.body
 */
app.use(function (req, res, next) {
    console.log(48, '请求的路径', req.originalUrl)
    req.body =
        req.method == "GET" ?
        req.query :
        req.method == "POST" ?
        req.body :
        req.params;
    req.token = req.headers.token || req.body.token || req.query.token || "";
    let requestInfo = {
        path: req.originalUrl,
        method: req.method,
        ip: req.ip,
        token: req.token || "",
        requestParams: JSON.stringify(req.body),
    };
    log(38, requestInfo);
    next();
});

routers(app);
app.use(function (res, req, next) {
    if (res.path.indexOf("/favicon.ico") != -1) next();
    let err = new Error(" 404 Not Found ");
    next(err);
});
app.use(function (err, req, res, next) {
    let errMsg = {
        respCode: err.respCode || 500,
        router: req.path,
        respMsg: err.respMsg,
    };
    process.env.NODE_ENV == "dev" ? (errMsg.error = err.stack) && res.json(errMsg) : (errMsg.error = err.message);
    log(83, errMsg);
});
const server = http.createServer(app);
server.listen(process.env.PORT || config.port);
server.on("listening", function () {
    const addr = server.address();
    log(`app listen on port ${addr.port}....... 当前运行的环境是：${process.env.NODE_ENV}`);
});